package com.xiaohui.log;

import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@Aspect
@ConditionalOnProperty(name = "log.enable", havingValue = "true", matchIfMissing = true)
public class LogAspect {

    @Pointcut("execution(* com.xiaohui.*.controller.*Controller.*(..)) || execution(* com.xiaohui.*.service.*Service.*(..))")
    private void pointcut() {
    }

    @Around("pointcut()")
    private Object around(ProceedingJoinPoint point) throws Throwable {
        Object[] args = point.getArgs();
        String req = new Gson().toJson(args);
        MethodSignature methodSignature = (MethodSignature) point.getSignature();
        String methodName = methodSignature.getDeclaringType().getName() + "." + methodSignature.getName();
        log.info("请求方法{}, req：{}", methodName, req);
        long startTime = System.currentTimeMillis();
        Object responseObj = point.proceed();
        String response = new Gson().toJson(responseObj);
        long endTime = System.currentTimeMillis();
        log.info("{},response:{},costTime:{}", methodName, response, endTime - startTime);
        return responseObj;
    }

}
